package com.gzw.jackyweather.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Binder;
import android.os.Environment;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.widget.Toast;

import com.gzw.jackyweather.MainActivity;
import com.gzw.jackyweather.R;
import com.gzw.jackyweather.WeatherActivity;

import java.io.File;
import java.text.DecimalFormat;

/**
 * 一个后台下载，更新notification进度的服务。
 */

public class DownLoadService extends Service {

    private DownLoadTask downLoadTask;

    private String downLoadUrl;

    private DecimalFormat df = new DecimalFormat("#.00");

    private DownLoadListener listener = new DownLoadListener() {


        //更新下载的进度
        @Override
        public void onProgress(int progress, long download, long total) {
            getNotifiCationManager().notify(1, getNotifiation("下载中...", progress, download, total));
        }

        @Override
        public void onSuccess() {
            downLoadTask = null;
            //下载成功关闭通知，新增加一个下载成功的通知。
            stopForeground(true);
            getNotifiCationManager().notify(1, getNotifiation("下载成功", -1, 0, 0));
            Toast.makeText(DownLoadService.this, "下载成功", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onFailed() {
            downLoadTask = null;
            stopForeground(true);
            getNotifiCationManager().notify(1, getNotifiation("下载失败", -1, 0, 0));
            Toast.makeText(DownLoadService.this, "下载失败", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onPaused() {
            downLoadTask = null;
            Toast.makeText(DownLoadService.this, "暂停", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCanceled() {
            downLoadTask = null;
            Toast.makeText(DownLoadService.this, "取消", Toast.LENGTH_SHORT).show();

        }
    };

    private DownLoadBinder mBinder = new DownLoadBinder();

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    public class DownLoadBinder extends Binder {

        //开始下载
        public void startDownLoad(String url) {
            if (downLoadTask == null) {
                downLoadUrl = url;
                downLoadTask = new DownLoadTask(listener);
                downLoadTask.execute(url);
                //设置Notification的ID为1，服务中使用通知，
                startForeground(1, getNotifiation("下载中...", 0, 0, 0));
                Toast.makeText(DownLoadService.this, "下载中...", Toast.LENGTH_SHORT).show();
            }
        }

        //暂停下载
        public void pauseDownLoad() {
            if (downLoadTask != null) {
                downLoadTask.pausedDownLoad();
            }
        }

        //取消下载，把文件删除
        public void cancelDownLoad() {
            if (downLoadTask != null) {
                downLoadTask.cancelDownLoad();
            } else {
                if (downLoadUrl != null) {
                    String fileName = downLoadUrl.substring(downLoadUrl.lastIndexOf("/"));
                    String directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath();
                    File file = new File(directory + fileName);
                    if (file.exists()) {
                        file.delete();
                    }

                    getNotifiCationManager().cancel(1);
                    stopForeground(true);
                    Toast.makeText(DownLoadService.this, "取消下载", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    //获取通知管理类
    private NotificationManager getNotifiCationManager() {
        return (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    }

    private Notification getNotifiation(String title, int progress, long a, long b) {
        Intent intent = new Intent(this, WeatherActivity.class);
        PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setSmallIcon(R.mipmap.ic_launcher);
        builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
        builder.setContentIntent(pi);
        builder.setContentTitle(title);
        if (progress > 0) {
            long yu = 1024 * 1024;
            if (a == b && b != 0) {
                builder.setContentText("下载完成");
                builder.setProgress(100, progress, false);
            } else {
                builder.setContentText(df.format((double) a / yu)
                        + "M / " + df.format((double) b / yu) + "M");
                builder.setProgress(100, progress, false);
            }
        }
        return builder.build();
    }

    public DownLoadService() {
    }
}
